﻿Imports System.Timers
Imports HslCommunication
Imports HslCommunication.LogNet
Imports HslCommunication.Profinet.Siemens
Imports Newtonsoft.Json
Imports Newtonsoft.Json.Linq

Public Class UCtmjInfo
    Public agv_website As String
    '西门子1200对象
    Public StripperPLC_UC As SiemensS7Net
    'PLC是否连接成功
    Public StripperPlcConFLG_UC As Boolean = False

    Dim objagvlog As New clsAgvLog

    Dim objClsSysParam As New clsSysParam

    Dim objClsTmj As New clsTmj

    Private Heart As Boolean = True

    Public reset_last_flg As Boolean = False
    Public reset_start_time As DateTime
    Public tmj_task_step_id As String = String.Empty
    Public agv_id As String = String.Empty
    Public agv_move_1 As Boolean = False
    'Public agv_move_2 As Boolean = False
    Dim httphelper As New HttpHelper
    'Public WithEvents tmPLC As New System.Timers.Timer(1000)
    Public logfile As ILogNet            'log文件
    Public thTime As New Threading.Thread(AddressOf tmPLC_Elapsed)
    Public plcflg As Boolean = False
    Public Sub New()
        If Not HslCommunication.Authorization.SetAuthorizationCode("e3e27344-1a9f-4d8b-b4fc-da5cae4b99bf") Then
            'writeErrlog(EquipID, "Communication没有授权，只能使用24小时。")
        End If
        ' 此调用是设计器所必需的。
        InitializeComponent()
    End Sub

    Private Function setTask(agv As String, oper As Integer) As String
        Try
            Dim msg As String
            If String.IsNullOrEmpty(agv_website) = False Then
                Dim url As String = agv_website & "AGVAPI?do=SetAGVState&agv=" & agv & "&oper=" & oper
                Dim rtn As String = httphelper.HttpGet(url, "")
                Dim jo As JObject = JsonConvert.DeserializeObject(rtn)
                Dim code As String = jo("code").ToString() '输出0
                msg = jo("msg").ToString() '输出ok
            Else
                msg = "请联系工作人员，配置agv网址"
            End If
            Return msg
        Catch ex As Exception
            logfile.WriteError("UCtmjinfo.setTask:" & ex.Message)
            Return ""
        End Try

    End Function

    Private Function readStripperPlc(place As String) As String
        Try
            '执行plc读取操作
            'If StripperPlcConFLG_UC Then
            Return readStripper(place, StripperPLC_UC)
            'Else
            '    Return String.Empty
            'End If
        Catch ex As Exception
            logfile.WriteError("UCtmjinfo.readStripperPlc:" & ex.Message)
            Return ""
        End Try

    End Function

    Private Function readStripper(place As String, plc As SiemensS7Net) As String
        Try
            '	RGV当前状态	Int	2.0
            Dim status As String = plc.ReadBool(place).Content
            Return status
        Catch ex As Exception
            logfile.WriteError("UCtmjinfo.readStripper:" & ex.Message)
            Return ""
        End Try

    End Function
    Private Function readStripperByte(place As String, plc As SiemensS7Net) As String
        Try
            '	RGV当前状态	Int	2.0
            Dim status As String = plc.ReadByte(place).Content
            Return status
        Catch ex As Exception
            logfile.WriteError("UCtmjinfo.readStripperByte:" & ex.Message)
            Return ""
        End Try

    End Function
    Private Function writeStripperBoolPlc(place As String, val As Boolean) As Boolean
        Try
            'If StripperPlcConFLG_UC Then
            Return WriteStripperBool(place, val, StripperPLC_UC)
            'Else
            '    Return False
            'End If
        Catch ex As Exception
            logfile.WriteError("UCtmjinfo.writeStripperBoolPlc:" & ex.Message)
            Return ""
        End Try

    End Function
    Private Function WriteStripperBool(place As String, val As Boolean, plc As SiemensS7Net) As Boolean
        Try
            '查询脱模机状态等条件
            'Dim dt As DataTable = objStripper.getList(strippername)
            'If dt.Rows(0)("status").ToString().Equals("1") Then
            '    '如果满足条件 则进行更新
            'End If
            Dim OperR As OperateResult = plc.Write(place, val)
            Return OperR.IsSuccess
        Catch ex As Exception
            logfile.WriteError("UCtmjinfo.WriteStripperBool:" & ex.Message)
            Return False
        End Try

    End Function
    Dim _count As Integer = 1
    Private Sub tmPLC_Elapsed() 'sender As Object, e As ElapsedEventArgs) Handles tmPLC.Elapsed
        While plcflg
            'logfile.WriteDebug(_count)
            _count = _count + 1
            Try
                StripperPlcConFLG_UC = StripperPLC_UC.ReadBool("DB47.DBX0.4").IsSuccess
                If StripperPlcConFLG_UC Then '通讯检测（读取）
                    lblConnPlcRtn.Text = "通讯中......"
                    Dim bbxx As Boolean = writeStripperBoolPlc("DB47.DBX11.2", True)
                    '异常状态（读取）
                    Dim rtn00 As String = readStripperPlc("DB1.1.11")
                    lblErrorRtn.Text = rtn00
                    'Threading.Thread.Sleep(500)
                    '脱模机忙闲状态（读取）
                    Dim rtn11 As String = readStripperPlc("DB47.DBX0.0")
                    lblStatusRtn.Text = rtn11
                    'Threading.Thread.Sleep(500)
                    '监听支座型号（读取）
                    Dim bb2 As String = readStripperByte("DB47.DBX10", StripperPLC_UC)
                    lblsmRtn.Text = bb2
                    'Threading.Thread.Sleep(500)
                    '监听AGV到位状态（读取）
                    Dim bb1 As String = readStripperPlc("DB47.DBX11.0")
                    lblAgvArrvel1Rtn.Text = bb1
                    'Threading.Thread.Sleep(500)
                    '监听脱模机拿取支座完成状态（读取）
                    Dim rtn1 As String = readStripperPlc("DB47.DBX0.1")
                    lblPickRtn.Text = rtn1
                    If rtn1 = True.ToString() Then
                        If agv_move_1 = False Then
                            '更新数据库表支座拿取结果字段
                            If String.IsNullOrEmpty(tmj_task_step_id) = False And String.IsNullOrEmpty(agv_id) = False Then
                                objClsTmj.update_tmj_pick_read(True, tmj_task_step_id)
                                '执行agv启动
                                Dim rtnmsg As String = setTask(agv_id, 1)
                                If rtnmsg.Equals("ok") Then
                                    objClsTmj.update_agv_start1(1, tmj_task_step_id)
                                    agv_move_1 = True
                                    objClsSysParam.update_agv_tmj(agv_id, tmj_task_step_id)
                                Else
                                    lblMsgTxt.Text = rtnmsg
                                End If
                            End If
                        End If
                    End If
                    'Threading.Thread.Sleep(500)
                    '监听AGV到位状态（读取）
                    Dim bb3 As String = readStripperPlc("DB47.DBX11.3")
                    lblAgvArrvel2Rtn.Text = bb3
                    If bb3 = True.ToString() Then
                        '更新数据库表agv到位字段
                        If String.IsNullOrEmpty(tmj_task_step_id) = False Then
                            lblMsgTxt.Text = "agv到位结果：" & bb3.ToString()
                            objClsTmj.update_tmj_stop_write(True, tmj_task_step_id)
                        End If
                    End If
                    'Threading.Thread.Sleep(500)
                    '监听脱模机脱模完成状态（读取）
                    Dim rtn2 As String = readStripperPlc("DB47.DBX0.2")
                    lblDownRtn.Text = rtn2
                    If rtn2 = True.ToString() Then
                        'If agv_move_2 = False Then
                        '更新数据库表脱模完成字段
                        If String.IsNullOrEmpty(tmj_task_step_id) = False Then
                            objClsTmj.update_tmj_drop_read(True, tmj_task_step_id)
                        End If
                        '执行agv离开plc写入
                        'Dim bbas As Boolean = writeStripperBoolPlc("DB47.DBX11.1", True)
                        'If bbas Then
                        '    writeStripperBoolPlc("DB47.DBX11.0", False)
                        '    writeStripperBoolPlc("DB47.DBX11.3", False)
                        '更新数据库表agv到位字段
                        'If String.IsNullOrEmpty(tmj_task_step_id) = False Then
                        '        objClsTmj.update_tmj_received_write(True, tmj_task_step_id)
                        '    End If
                        '执行agv离开
                        'Dim rtnmsg1 As String = setTask(agv_id, 1)
                        'If rtnmsg1.Equals("ok") Then
                        'reset_last_flg = True
                        'reset_start_time = Now()
                        'objClsTmj.update_agv_start2(1, tmj_task_step_id)
                        'agv_move_2 = True
                        'tmj_task_step_id = String.Empty
                        'agv_id = String.Empty
                        'Else
                        'lblMsgTxt.Text = rtnmsg1
                        'End If
                        'End If
                        'End If

                    End If
                    '监听AGV离开状态（读取）
                    Dim bbb1 As String = readStripperPlc("DB47.DBX11.1")
                    lblLeaveRtn.Text = bbb1
                    If bbb1 = True.ToString() Then
                        reset_last_flg = True
                        reset_start_time = Now()
                        tmj_task_step_id = String.Empty
                        agv_id = String.Empty
                    End If
                    If reset_last_flg = True Then
                        If Math.Abs(DateDiff(DateInterval.Second, reset_start_time, Now)) >= 20 Then
                            writeStripperBoolPlc("DB47.DBX11.1", False)
                            reset_last_flg = False
                            agv_move_1 = False
                            'agv_move_2 = False
                        End If
                    End If
                Else

                    lblConnPlcRtn.Text = "通讯失败，请检查网络！"
                    Dim localip As String = GetIPAddr()
                    objagvlog.add(localip, "脱模机", "通讯失败", "脱模机通讯失败")
                    TextBox1.Text &= Now.ToString() + vbCrLf
                    'Dim rtnconnser As OperateResult = StripperPLC_UC.ConnectServer()
                    'If rtnconnser.IsSuccess = False Then
                    '    DBacs.Disconnect()
                    '    Application.Restart()
                    'End If
                End If
            Catch ex As Exception
                logfile.WriteError("UCtmjinfo.tmPLC_Elapsed:" & ex.Message)
            End Try
        End While
    End Sub
End Class
